package fu.capstone.hanoicityguide.dataaccess.bus;

import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import fu.capstone.hanoicityguide.business.model.Bus;
import fu.capstone.hanoicityguide.dataaccess.base.BaseDAOImpl;
import fu.capstone.hanoicityguide.dataaccess.base.DatabaseHelper;

public class BusDAOImp extends BaseDAOImpl implements BusDAO{

	private SQLiteDatabase database;
	private DatabaseHelper dbHelper;
	private Context context;
	
	public BusDAOImp(Context ctx) {
		super(ctx);
		// TODO Auto-generated constructor stub
	}
	
	@Override
	public ArrayList<Bus> listBus(String filter, String sorter) {
		// TODO Auto-generated method stub
		Cursor cursor = null;
		ArrayList<Bus> arrResult = new ArrayList<Bus>();
		
		try {
			dbHelper = connectDB();
			database = dbHelper.getReadableDatabase();
			String queryBus = "SELECT * FROM Transport " +
					"LEFT JOIN TransportCategory ON Transport.[TransportID] = TransportCategory.[Id]  " +
					"WHERE TransportCategory.[TransportName] == \"Bus\"";

			cursor = database.rawQuery(queryBus, null);
			if (cursor != null) {
				if (cursor.moveToFirst()) {
					do {

						Bus bus = new Bus();
						bus.setId(cursor.getInt(cursor
								.getColumnIndex("Id")));
						bus.setName(cursor.getString(cursor
								.getColumnIndex("Name")));
						bus.setDesc(cursor.getString(cursor
								.getColumnIndex("Description")));
						bus.setIconPath(cursor.getString(cursor
								.getColumnIndex("IconPath")));

						arrResult.add(bus);
					} while (cursor.moveToNext());
				}
			}
		} catch (Exception e) {
			Log.v("Can't query DB", e.toString());
		} finally {
			closeDB(database, dbHelper);
		}
		
		return arrResult;
	}

	@Override
	public Bus browseBus(int busID) {
		// TODO Auto-generated method stub
		Cursor cursor = null;
		Bus bus = new Bus();
		
		try {
			dbHelper = connectDB();
			database = dbHelper.getReadableDatabase();
			String queryBus = "SELECT * FROM Transport " +
					"LEFT JOIN TransportCategory ON Transport.[Id] = TransportCategory.[Id]  " +
					"WHERE TransportCategory.[TransportName] == \"Bus\"";

			cursor = database.rawQuery(queryBus, null);
			if (cursor != null) {
				if (cursor.moveToFirst()) {
					do {					
						bus.setId(cursor.getInt(cursor
								.getColumnIndex("Id")));
						bus.setFirstLeg(cursor.getString(cursor
								.getColumnIndex("FirstLeg")));
						bus.setSecondLeg(cursor.getString(cursor
								.getColumnIndex("SecondLeg")));		
						bus.setPrice(cursor.getString(cursor
								.getColumnIndex("Price")));
					} while (cursor.moveToNext());
				}
			}
		} catch (Exception e) {
			Log.v("Can't query DB", e.toString());
		} finally {
			closeDB(database, dbHelper);
		}
		
		return bus;
	}

}
